'use client'

import { useState } from 'react'
import { z } from 'zod'
import { useAuth } from '@/contexts/auth-context'
import { StarRating } from '@/components/ui/star-rating'
import { Button } from '@/components/ui/button'
import { MessageSquare, Send } from 'lucide-react'

const reviewSchema = z.object({
  rating: z.number().min(1, '请选择评分').max(5, '评分不能超过5星'),
  comment: z.string()
    .min(5, '评论至少需要5个字符')
    .max(500, '评论不能超过500个字符')
})

type ReviewForm = z.infer<typeof reviewSchema>

interface ReviewFormProps {
  toolId: string
  onReviewAdded?: () => void
}

export function ReviewForm({ toolId, onReviewAdded }: ReviewFormProps) {
  const { user: authUser } = useAuth()
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [message, setMessage] = useState<{ type: 'success' | 'error', text: string } | null>(null)
  const [rating, setRating] = useState(0)
  const [comment, setComment] = useState('')

  const handleRatingChange = (newRating: number) => {
    setRating(newRating)
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()

    if (!authUser) {
      setMessage({
        type: 'error',
        text: '请先登录后再评价'
      })
      return
    }

    // 验证表单
    if (!rating) {
      setMessage({
        type: 'error',
        text: '请选择评分'
      })
      return
    }

    if (!comment.trim()) {
      setMessage({
        type: 'error',
        text: '请填写评论内容'
      })
      return
    }

    if (comment.trim().length < 5) {
      setMessage({
        type: 'error',
        text: '评论至少需要5个字符'
      })
      return
    }

    if (comment.length > 500) {
      setMessage({
        type: 'error',
        text: '评论不能超过500字符'
      })
      return
    }

    setIsSubmitting(true)
    setMessage(null)

    try {
      const response = await fetch(`/api/tools/${toolId}/reviews`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          rating,
          comment: comment.trim(),
          userId: authUser.id,
          userName: authUser.name
        }),
      })

      const result = await response.json()

      if (response.ok) {
        setMessage({
          type: 'success',
          text: '评价提交成功！'
        })
        setRating(0)
        setComment('')
        onReviewAdded?.()
      } else {
        setMessage({
          type: 'error',
          text: result.error || '提交失败，请重试'
        })
      }
    } catch (error) {
      setMessage({
        type: 'error',
        text: '网络错误，请重试'
      })
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
    <div className="bg-white border border-gray-200 rounded-lg p-6">
      <div className="flex items-center gap-2 mb-4">
        <MessageSquare className="h-5 w-5 text-blue-500" />
        <h3 className="text-lg font-semibold text-gray-900">写评价</h3>
      </div>

      <form onSubmit={handleSubmit} className="space-y-4">
        {/* 评分 */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            评分 *
          </label>
          <StarRating
            rating={rating}
            onRatingChange={handleRatingChange}
            size="lg"
          />
          {rating === 0 && message?.type === 'error' && (
            <p className="text-red-500 text-sm mt-1">请选择评分</p>
          )}
        </div>

        {/* 评论 */}
        <div>
          <label htmlFor="comment" className="block text-sm font-medium text-gray-700 mb-2">
            评论 *
          </label>
          <textarea
            value={comment}
            onChange={(e) => setComment(e.target.value)}
            id="comment"
            rows={4}
            className={`w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none ${
              comment.length > 500 ? 'border-red-300' : 'border-gray-300'
            }`}
            placeholder="分享您使用这个工具的体验..."
            maxLength={500}
          />
          <div className="flex justify-between items-center mt-1">
            {comment.trim() === '' && message?.type === 'error' && (
              <span className="text-red-500 text-xs">请填写评论内容</span>
            )}
            <div className="flex-1"></div>
            <span className={`text-xs ${comment.length > 500 ? 'text-red-500' : 'text-gray-500'}`}>
              {comment.length}/500
            </span>
          </div>
        </div>

        {/* 消息提示 */}
        {message && (
          <div className={`p-3 rounded-md text-sm ${
            message.type === 'success' 
              ? 'bg-green-50 text-green-700 border border-green-200' 
              : 'bg-red-50 text-red-700 border border-red-200'
          }`}>
            {message.text}
          </div>
        )}

        {/* 提交按钮 */}
        <div className="flex justify-end">
          <Button 
            type="submit" 
            disabled={isSubmitting || rating === 0}
            className="flex items-center gap-2"
          >
            <Send className="h-4 w-4" />
            {isSubmitting ? '提交中...' : '提交评价'}
          </Button>
        </div>
      </form>
    </div>
  )
}
